import { Vector3 } from "../base_frame/math/Vector3";
import { LightCube } from "./LightCube";

export class PointLightCube extends LightCube {
    protected readonly VS: string =
        "attribute vec4 a_Position;\n" +
        "attribute vec4 a_Color;\n" +
        "attribute vec4 a_Normal;\n" +
        "varying vec3 v_Position;\n" +
        "varying vec3 v_Normal;\n" +
        "varying vec4 v_Color;\n" +
        "uniform mat4 u_MvpMatrix;\n" +
        "uniform mat4 u_NormalMatrix;\n" +

        "void main(){\n" +
        "   v_Normal = vec3(u_NormalMatrix * a_Normal);\n" +
        "   vec4 realPos = u_MvpMatrix * a_Position;\n" +
        "   v_Position = realPos.xyz;\n" +
        "   v_Color = a_Color;\n" +
        "   gl_Position = realPos;\n" +
        "}\n";

    protected readonly FS: string =
        "precision mediump float;\n" +
        "varying vec4 v_Color;\n" +
        "varying vec3 v_Position;\n" +
        "varying vec3 v_Normal;\n" +
        "uniform vec3 u_LightPosition;\n" +
        "uniform vec3 u_LightColor;\n" +
        "uniform vec3 u_AmbientColor;\n" +
        "void main(){\n" +
        // "   vec3 lightDir = normalize(v_Position - u_LightPosition);\n" +
        "   vec3 lightDir = normalize(u_LightPosition - v_Position);\n" +
        "   vec3 normal = normalize(v_Normal);\n" +
        "   vec3 diffuseColor = max(dot(lightDir,normal),0.0)*u_LightColor*v_Color.rgb;\n" +
        "   vec3 realColor = diffuseColor + u_AmbientColor*v_Color.rgb;\n" +
        "   gl_FragColor = vec4(realColor, v_Color.a);\n" +
        "}\n";


    private _lightPosition:Vector3 = new Vector3(3.0,2.2,0.0);

    private u_LightPosition:WebGLUniformLocation;
    
    initRef(gl: WebGL2RenderingContext | WebGLRenderingContext): void {
        //@ts-ignore
        let program = gl.program;
        this.a_Position = gl.getAttribLocation(program, "a_Position");
        this.a_Color = gl.getAttribLocation(program, "a_Color");
        this.a_Normal = gl.getAttribLocation(program, "a_Normal");
        this.u_LightColor = gl.getUniformLocation(program, "u_LightColor");
        this.u_AmbientColor = gl.getUniformLocation(program, "u_AmbientColor");
        this.u_LightPosition = gl.getUniformLocation(program, "u_LightPosition");
        this.u_NormalMatrix = gl.getUniformLocation(program, "u_NormalMatrix");
    }

    initValue(gl: WebGL2RenderingContext | WebGLRenderingContext) {
        let vec3 = this._lightPosition;
        gl.uniform3f(this.u_LightPosition, vec3.x, vec3.y, vec3.z);
        gl.uniform3f(this.u_LightColor, 1.0, 1.0, 1.0);
        gl.uniformMatrix4fv(this.u_NormalMatrix, false, this.normalMatrix.elements);
        gl.uniform3f(this.u_AmbientColor, 0.2, 0.2, 0.2);
    }
}